package com.example.demo.common;

import com.example.demo.entity.Time;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * Created with IntelliJ IDEA.
 * Description: 时间类
 */
public class ArtTimeUtil {

    // 默认月份时间
    private static final int[] dayOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    // 传时间参数，对时间内容进行判断与校正
    public static void timeCheck(Time time){
        LocalDateTime localDateTime = LocalDateTime.now();
        // 年份最多是下一年
        if(time.getYear() == null || time.getYear() < localDateTime.getYear() || time.getYear() > localDateTime.getYear() + 1) {
            time.setYear(localDateTime.getYear());
        }
        // 月份必须在 1 ~ 12 之间
        if(time.getMonth() == null || time.getMonth() < 1 || time.getMonth() > 12) {
            time.setMonth(localDateTime.getMonthValue());
        }
        int year = time.getYear();
        int month = time.getMonth();
        int dayMax = dayOfMonth[month];
        if(month == 2) {
            if(year % 400 == 0 || (year % 400 != 0 && year % 4 == 0)) {
                dayMax += 1;
            }
        }
        // 按照月份限制天数
        if(time.getDay() == null || time.getDay() < 1 || time.getDay() > dayMax) {
            time.setDay(localDateTime.getDayOfMonth());
        }
        // 限制时间
        if(time.getHour() == null || time.getHour() < 0 || time.getHour() >= 24) {
            time.setHour(localDateTime.getHour());
        }
        // 限制分钟
        if(time.getMinute() == null || time.getMinute() < 0 || time.getMinute() >= 60) {
            time.setMinute(localDateTime.getMinute());
        }
        time.setSecond(0);
    }

    // 包装时间方法，将 Time 对象转为 LocalDateTime 对象
    public static LocalDateTime getTimeToLocalDateTime(Time time) {
        return LocalDateTime.of(time.getYear(), time.getMonth(), time.getDay(), time.getHour(), time.getMinute(), time.getSecond());
    }

    // 包装时间方法，将 Time 对象转为 LocalDateTime 对象，并获取发布时间和当前时间之间的时间戳
    public static Duration getTimeToDuration(Time time) {
        LocalDateTime nowTime = LocalDateTime.now();
        LocalDateTime userTime = getTimeToLocalDateTime(time);
        return Duration.between(nowTime, userTime);
    }
}
